from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import loader
# Create your views here.

"""创建应用之后，需要在工程settings文件下安装应用，并在urls文件下添加路由"""


def cookie_session(request):
    # 设置session
    request.session['itcast'] = 'python'
    # 读取session
    print(request.session.get('itcast'))
    return HttpResponse('ok')


def register(request):
    # 在settings里关闭中间件csrf,用post方法请求时，不用设置CSRF cookie
    if request.method == 'GET':
        return HttpResponse('GET请求')
    else:
        return HttpResponse('POST请求')


def my_decorator(func):
    # func相当于get,post
    # func = my_decorator(func)
    # get = my_decorator(get)
    # *args, **kwargs 是通用形式参数，实参可以不传
    def wrapper(self, request, *args, **kwargs):
        print("自定义装饰器被调用了")
        print("请求的方法", request.method)
        print("请求路径%s" % request.path)
        # get() ===> GET请求,POST请求
        return func(self, request, *args, **kwargs)
    return wrapper


# 类视图是将业务逻辑以类的方式实现,这里还使用装饰器
# get = my_decorator(get)
class RegisterView(View):
    @my_decorator
    def get(self, request):
        return HttpResponse('GET请求')

    @my_decorator
    def post(self, request):
        return HttpResponse('POST请求')

    def put(self, request):
        return HttpResponse('put请求')


# 类视图Mixin扩展类
class ListModelMixin(object):
    # list扩展类
    def list(self, request, *args, **kwargs):
        print('list函数')


class CreateModelMixin(object):
    # create扩展类
    def create(self, request, *args, **kwargs):
        print('create函数')


# 继承扩展类，复用list和create方法
class BookView(CreateModelMixin, ListModelMixin, View):
    # get请求
    def get(self, request):
        # 调用扩展类中的方法
        self.list(request)
        return HttpResponse('OK')

    # post请求
    def post(self, request):
        # 调用扩展类中的方法
        self.create(request)
        return HttpResponse('OK')


def demo_view(request):
    print('view 视图被调用')
    return HttpResponse('OK')


"""
模板使用：
1.视图函数
2.添加url
3.模板获取数据
"""

"""
http://127.0.0.1:8000/index/
渲染结果：
hello world python
"""


def index(request):
    # 获取模板
    # temp = loader.get_template('index.html')
    # 渲染模板
    # context = {'itcast': 'python'}
    # return HttpResponse(temp.render(context))

    # 与上面的方式效果一样
    context = {'itcast': 'python'}
    return render(request, 'index.html', context)